package com.jt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.service.ItemService;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;

    @Override
    public PageResult getItemList(PageResult pageResult) {
        //判断用户是否有值（高级API）
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();//条件构造器
        //动态模糊查询
        queryWrapper.like(flag, "title", pageResult.getQuery());
        //MP分页对象                                 页数            条数
        IPage<Item> page = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        //分页查询
        page = itemMapper.selectPage(page, queryWrapper);
        long total = page.getTotal();//记录
        List<Item> rows = page.getRecords();//查询结果
        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        Item item = itemVO.getItem();
        item.setStatus(true);
        //MP原则：入库之后动态回显数据
        itemMapper.insert(item);
        //itemDesc对象入库
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);
    }

    @Override
    @Transactional
    public void updateItemStatus(Item item) {
        Integer id = item.getId();
        Item item1 = new Item();
        item1.setId(id).setStatus(item.getStatus());
        itemMapper.updateById(item1);
    }

    @Override
    @Transactional
    public void deleteItemById(Integer id) {
        itemMapper.deleteById(id);
    }

    @Override
    @Transactional
    /*id当作条件其他不为null的数据进行修改*/
    public void updateItemById(Item item) {
        itemMapper.updateById(item);
    }
}
